/**  
 * All rights Reserved, Designed By http://www.pete-cat.com/
 * @Title:  LogStoreHandler.java   
 * @Package com.petecat.ruleengine.core.aop.log   
 * @Description:TODO(用一句话描述该文件做什么)   
 * @author: 成都皮特猫科技     
 * @date:2017年12月19日 上午10:51:51   
 * @version V1.0 
 * @Copyright: 2017 www.pete-cat.com Inc. All rights reserved. 
 * 注意：本内容仅限于成都皮特猫信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */  
package com.petecat.ruleengine.core.aop.log.handler;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.petecat.ruleengine.core.aop.log.model.LogDataModel;
import com.petecat.ruleengine.core.util.RequestUtils;
import com.petecat.ruleengine.protocol.sso.vo.SsoUserInfoVO;

/**   
 * @ClassName:  LogStoreHandler   
 * @Description:日志存储控制
 * @author: admin
 * @date:   2017年12月19日 上午10:51:51   
 */
public class LogStoreHandler {

	private static Logger vistLogger = LoggerFactory.getLogger("vistLog");

	private static Logger logger = LoggerFactory.getLogger(LogStoreHandler.class);
	
	//临时存放对象
	private static ThreadLocal<LogDataModel> currentLocalLog = ThreadLocal.withInitial(() -> null);
	
	/**   
	 * @Title: storeLog   
	 * @Description: 存储日志
	 * @param logDataModel
	 * @return void     
	 */
	public  static void storeLog(LogDataModel logDataModel) {
		currentLocalLog.set(logDataModel);
	}

	/**   
	 * @Title: getLog   
	 * @Description: 获取日志
	 * @param logDataModel
	 * @return void     
	 */
	public  static LogDataModel getLog() {
		return currentLocalLog.get();
	}
	
	
	public static LogDataModel gernateInitLog(String clsName,String method,HttpServletRequest request) {
		LogDataModel logDataModel = new LogDataModel();
		logDataModel.setCls(clsName);
		logDataModel.setMethod(method);
		logDataModel.setType(request.getMethod());
		logDataModel.setRequestData(RequestUtils.getRequestMapForRequest(request));
		logDataModel.setUrlParam(request.getQueryString());
		logDataModel.setExecStartTime(System.nanoTime()/1000000);
		logDataModel.setIp(RequestUtils.getIpAddress(request));
		logDataModel.setAuthorization(request.getHeader("Authorization"));
		SsoUserInfoVO user = (SsoUserInfoVO) request.getAttribute("CURRENT_USER_INFO");
		if(user != null) {
			try {
				logDataModel.setOpUserInfo(user);
			} catch (Exception e) {
			}
		}
		return logDataModel;
	}

	/**   
	 * @Title: remove   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @return void     
	 */
	public static void remove() {
		currentLocalLog.remove();		
	}

	 /**   
	 * @Title: writerLog   
	 * @Description: 写日志   
	 * @param dataModel
	 * @return void     
	 */
	public static void writerLog(LogDataModel dataModel) {
		try {
			if(dataModel != null) {
			     vistLogger.info(JSON.toJSONString(dataModel));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}

}
